package cc.bookcloud.tool.ocr.controller;

import cc.bookcloud.tool.ocr.common.JResult;
import com.alibaba.fastjson.JSONObject;
import com.vladsch.flexmark.html.HtmlRenderer;
import com.vladsch.flexmark.parser.Parser;
import com.vladsch.flexmark.util.ast.Node;
import com.vladsch.flexmark.util.data.MutableDataSet;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import okio.Buffer;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.springframework.web.bind.annotation.*;




@Slf4j
@RestController
@Api(tags = "调用deepseek API调试接口")
@RequestMapping("/deepseek")
public class DeepseekAPIController {

    private static final String API_URL = "https://api.deepseek.com/v1/chat/completions";
    private static final String API_KEY = "sk-d2c018e5df3d491d9a28afa51d131947"; // 替换为你的API密钥


   // 使用Post请求，发送一个JSON格式的请求体，并返回一个JSON格式的响应体。

    @GetMapping("/chat/api")
    public JResult<String> generateChat(HttpServletRequest requ) throws IOException {
        String askMsg = requ.getParameter("askMsg");
        if (askMsg == null || askMsg.trim().isEmpty()) {
            return JResult.build().failed("请求参数askMsg不能为空");
        }

        // ... 创建 OkHttpClient 实例的代码保持不变 ...  // 创建 OkHttpClient 实例
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(120, java.util.concurrent.TimeUnit.SECONDS) // 连接超时时间为 10 秒
                .readTimeout(60, java.util.concurrent.TimeUnit.SECONDS)    // 读取超时时间为 30 秒
                .writeTimeout(60, java.util.concurrent.TimeUnit.SECONDS)   // 写入超时时间为 30 秒
                .build();

        // 定义 JSON 数据
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        String json = "{\"model\": \"deepseek-chat\",\"messages\": [{\"role\": \"user\", \"content\": \"" + askMsg + "\"}]}";
        RequestBody body = RequestBody.create(JSON, json);
        // 构建请求
        Request request = new Request.Builder()
                .url(API_URL)
                .post(body)
                .addHeader("Authorization", "Bearer " + API_KEY)
                .build();

        //打印请求体
        Buffer buffer = new Buffer();
        body.writeTo(buffer);
        log.info("请求体: {}", buffer.readUtf8());
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                try (ResponseBody responseBody = response.body()) {
                    if (responseBody != null) {
                        String responseData = responseBody.string();
                        log.info("请求成功，响应数据: {}", responseData);
                        JSONObject jsonObject = JSONObject.parseObject(responseData);
                        String content = jsonObject.getJSONArray("choices").getJSONObject(0).getJSONObject("message").getString("content");
                        //  content = content.replaceAll("\n", "<br/>");
                        System.out.println(content);
                        // 使用flexmark将Markdown转换为HTML
                        MutableDataSet options = new MutableDataSet();
                        Parser parser = Parser.builder(options).build();
                        HtmlRenderer renderer = HtmlRenderer.builder(options).build();
                        Node document = parser.parse(content);
                        String html = renderer.render(document);
                        System.out.println("html:+\n" + html);
                        return JResult.build().ok(html);
                    }
                }
            } else {
                log.error("请求失败，错误码: {}", response.code());
                return JResult.build().failed("请求失败，错误码: " + response.code());
            }
        } catch (IOException e) {
            log.error("请求过程中发生异常", e);
            return JResult.build().failed("请求处理异常: " + e.getMessage());
        }

        return JResult.build().failed("未知错误，请检查请求参数和API配置");
    }

    protected List<JSONObject> list = null;

    // 定义一个get接口，输出json格式：name,email,role字段
    @GetMapping("/queryList")
    public String queryUserList() {
        //输出json格式：name,email,role字段
        //return "{\"name\":\"张三\",\"email\":\"zhangsan@example.com\",\"role\":\"管理员\"}";
        JSONObject row1 = new JSONObject();
        row1.put("id", 1);
        row1.put("name", "张三");
        row1.put("email", "zhangsan@example.com");
        row1.put("role", "管理员");
        // row2的记录
        JSONObject row2 = new JSONObject();
        row2.put("id", 2);
        row2.put("name", "李四");
        row2.put("email", "lisi@example.com");
        row2.put("role", "普通用户");
        // row3的记录
        JSONObject row3 = new JSONObject();
        row3.put("id", 3);
        row3.put("name", "王五");
        row3.put("email", "wangwu@example.com");
        row3.put("role", "普通用户");
        // 创建一个JSON数组，并将row1、row2和row3添加到其中
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 0);
        if (list == null) {
            list = new ArrayList();
            list.add(row1);
            list.add(row2);
            list.add(row3);

        }
        jsonObject.put("data", list);

        return jsonObject.toJSONString();

    }

    // deleteRowUser 接口，删除指定id的记录
    @GetMapping("/deleteRowUser")
    public String deleteRowUser(@RequestParam("id") int id) {
        log.info("deleteRowUser id:{}", id);
        // 遍历list，找到id匹配的记录，并删除
        for (int i = 0; i < list.size(); i++) {
            JSONObject row = list.get(i);
            if (row.getIntValue("id") == id) {
                list.remove(i);
                break;
            }
        }
        log.info("内存数据list:", list);
        return "{\"code\":0,\"msg\":\"删除成功\"}";

    }

    // deleteRowUser 接口，删除指定id的记录
//    @GetMapping("/updateRowUser")
//    public String updateRowUser(@RequestParam("id") int id) {
//        log.info("updateRowUser id:{}", id);
//        // 遍历list，找到id匹配的记录，并删除
//        for (int i = 0; i < list.size(); i++) {
//            JSONObject row = list.get(i);
//            if (row.getIntValue("id") == id) {
//
//                break;
//            }
//        }
//        log.info("内存数据list:", list);
//        return "{\"code\":0,\"msg\":\"删除成功\"}";
//
//    }


    @GetMapping("/updateRowUser")
    public String updateRowUser(@RequestParam("id") int id, @RequestParam("name") String name, @RequestParam("email") String email, @RequestParam("role") String role) {
        log.info("updateRowUser id:{},name:{},email:{},role:{}", id, name, email, role);
        for (int i = 0; i < list.size(); i++) {
            JSONObject row = list.get(i);
            if (row.getIntValue("id") == id) {
                row.put("name", name);
                row.put("email", email);
                row.put("role", role);
                return "{\"code\":0,\"msg\":\"更新成功\"}";
            }
        }
        return "{\"code\":1,\"msg\":\"更新失败\"}";

    }
}
